const http = require("http");
const fs = require("fs");
const path = require("path");
const os = require("os");

const UPLOAD_DIR = path.join(__dirname, "uploads");

// 创建 uploads 文件夹
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR);
}

// 解析 boundary
function getBoundary(header) {
  const items = header.split(";");
  for (let i = 0; i < items.length; i++) {
    let item = items[i].trim();
    if (item.startsWith("boundary=")) {
      return item.split("=")[1];
    }
  }
  return null;
}

// 启动服务器
const server = http.createServer((req, res) => {
  if (req.method === "OPTIONS") {
    // 处理 CORS 预请求
    res.writeHead(204, {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
      "Access-Control-Max-Age": 86400,
    });
    return res.end();
  }

  if (req.method === "POST" && req.url === "/upload") {
    const contentType = req.headers["content-type"];
    const contentLength = parseInt(req.headers["content-length"], 10);
    const boundary = getBoundary(contentType);

    if (!boundary) {
      res.writeHead(400, { "Content-Type": "text/plain" });
      return res.end("No boundary found");
    }

    let progress = 0;

    let rawData = Buffer.alloc(0);

    req.on("data", (chunk) => {
      progress += chunk.length;
      rawData = Buffer.concat([rawData, chunk]);

      // 输出上传进度（可传到客户端）
      const percent = ((progress / contentLength) * 100).toFixed(2);
      process.stdout.write(`\r上传进度: ${percent}%`);
    });

    req.on("end", () => {
      // 分隔字段
      const parts = rawData.toString().split(`--${boundary}`);
      for (let part of parts) {
        // 跳过不是文件字段的内容
        if (part.includes("filename=")) {
          const match = part.match(/filename="(.+)"/);
          if (!match) continue;

          const filename = match[1];
          const fileStart = part.indexOf("\r\n\r\n") + 4;
          const fileEnd = part.lastIndexOf("\r\n");
          const fileData = part.slice(fileStart, fileEnd);

          const fileBuffer = Buffer.from(fileData, "binary");

          const filePath = path.join(UPLOAD_DIR, filename);

          // 写入文件
          fs.writeFileSync(filePath, fileBuffer, "binary");
          console.log(`\n文件已保存：${filename}`);
        }
      }

      res.writeHead(200, {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      });
      res.end(JSON.stringify({ message: "文件上传成功！" }));
    });

    req.on("error", (err) => {
      console.error("上传失败：", err);
      res.writeHead(500, { "Content-Type": "text/plain" });
      res.end("服务器错误");
    });
  } else {
    // 非上传路由
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Not Found");
  }
});

const PORT = 5000;
server.listen(PORT, () => {
  console.log(`🚀 原生 Node.js 文件上传服务运行于 http://localhost:${PORT}`);
});
